<?php

class Core_Component_System_Method_Template {

    public function paginationHelper($tmpl, $records, $pagesize = 20) {
        $t = $GLOBALS[RC]->getLanguage();
        $args = array_merge($GLOBALS[RC]->getRequest()->getAllParameters(), array('pageindex' => '{index}', 'pagesize' => '{size}'));
        $url = $GLOBALS[RC]->getRouter()->buildUrl('*/*/*/*', $args);
        $result = new Soul_Template_Html_Pagination();
        return $result->setRecordCount($records)
                ->setPageSize($pagesize)
                ->setUrlFormat($url)
                ->setPageSizes(array(10, 20, 50, 100))
                ->setFirstPageText($t->__('pagination.firstPage'))
                ->setLastPageText($t->__('pagination.lastPage'))
                ->setNextPageText($t->__('pagination.nextPage'))
                ->setPrevPageText($t->__('pagination.prevPage'))
                ->setPageSizeText($t->__('pagination.pageSize'))
                ->setInformationTextFormat($t->__('pagination.information'))
                ->setPageIndex($GLOBALS[RC]->getRequest()->getParameter('pageindex', 1))
                ->setPageSize($GLOBALS[RC]->getRequest()->getParameter('pagesize', 20));
    }

    public function gridHelper($tmpl, $id = NULL, array $datasource = array()) {
        $args = array_merge($GLOBALS[RC]->getRequest()->getAllParameters(), array('sort' => '{field}', 'dir' => '{direction}'));
        $url = $GLOBALS[RC]->getRouter()->buildUrl('*/*/*/*', $args);
        $result = new Core_Template_Html_Grid();
        return $result->setId($id)
                ->setSortUrlFormat($url)
                ->setDataSource($datasource);
    }

    public function editorHelper($tmpl, $id, $name = NULL) {
        $result = new Core_Template_Html_Form_Editor();
        return $result->setId($id)->setName($name);
    }

    public function regionHelper($tmpl, $id = NULL, $name = NULL) {
        $result = new Core_Template_Html_Form_Region();
        return $result->setId($id)->setName($name);
    }

    public function industryHelper($tmpl, $id = NULL, $name = NULL) {
        $result = new Core_Template_Html_Form_Industry();
        return $result->setId($id)->setName($name);
    }

    public function beginBlockHelper($tmpl, $name = 'default') {
        $context = $tmpl->getContext();
        if (!$context->hasData('blocks')) {
            $context->setBlocks(array());
        }
        $context->setCurrentBlock($name);
        ob_start();
    }

    public function endBlockHelper($tmpl) {
        $context = $tmpl->getContext();
        if (isset($context['blocks']) && isset($context['current_block'])) {
            $blocks = $context->getBlocks();
            $blocks[$context->getCurrentBlock()] = ob_get_clean();
            $context->setBlocks($blocks);
        }
    }

    public function nextBlockHelper($tmpl, $name='default') {
        $tmpl->endBlock();
        $tmpl->beginBlock($name);
    }

    public function renderBlockHelper($tmpl, $name = 'default') {
        $result = '';
        $context = $tmpl->getContext();
        if (isset($context['blocks'])) {
            $blocks = $context->getBlocks();
            $result = Soul_Util_Array::removeItem($blocks, $name);
            $context->setBlocks($blocks);
        }
        return $result;
    }

    public function hasBlockHelper($tmpl, $name) {
        $context = $tmpl->getContext();
        if (isset($context['blocks'])) {
            $blocks = $context->getBlocks();
            return isset($blocks[$name]);
        }
        return FALSE;
    }

    public function beginScriptBlock($tmpl) {
        ob_start();
    }

    public function endScriptBlock($tmpl) {
        Soul_Template_Resource::getInstance()->addScriptBlock(ob_get_clean());
    }

    public function beginStartupScript($tmpl) {
        ob_start();
    }

    public function endStartupScript($tmpl) {
        Soul_Template_Resource::getInstance()->addStartupScript(ob_get_clean());
    }

    public function extendHelper($tmpl, $filename) {
        $file = file_exists($filename . '.phtml') ?
                $filename . '.phtml' :
                Soul_Util_FS::findFile($GLOBALS[RC]->getTemplateDirectories(), $filename . '.phtml');
        return Soul_Loader::loadInstance('Soul_Template_Template')->render($file);
    }

    public function loadTemplateHelper($tmpl, $filename) {
        $file = file_exists($filename . '.phtml') ?
                $filename . '.phtml' :
                Soul_Util_FS::findFile($GLOBALS[RC]->getTemplateDirectories(), $filename . '.phtml');

        return Soul_Loader::loadInstance('Soul_Template_Template')->render($file);
    }

    public function buildUrlHelper($tmpl, $url = '*/*/*/*', $arguments = array()) {
        return $GLOBALS[RC]->getRouter()->buildUrl($url, $arguments);
    }

    public function __Helper($tmpl, $key) {
        return $GLOBALS[RC]->getLanguage()->__($key);
    }

    public function __fHelper($tmpl, $langKey, $args) {
        $arr = array_merge(array($langKey), $args);
        return call_user_func_array(array($GLOBALS[RC]->getLanguage(), '__f'), $arr);
    }

    public function __tHelper($tmpl, $langKey, $args) {
        return '<{lang "' . $langKey . '"}>';
    }

    public function selectEnabledHelper($tmpl, $id, $name) {
        return $tmpl->select($id, $name)
                ->setOption($tmpl->__('system.button.enable'), CONSTANT_STATUS_ENABLED)
                ->setOption($tmpl->__('system.button.disable'), CONSTANT_STATUS_DISABLED);
    }

    public function selectBooleanHelper($tmpl, $id, $name) {
        return $tmpl->select($id, $name)
                ->setOption($tmpl->__('system.status.no'), '0')
                ->setOption($tmpl->__('system.status.yes'), '1');
    }

    public function imageUploadHelper($tmpl, $id, $name, $count = 1) {
        $result = new Core_Template_Html_Form_Upload_Image();
        return $result->setId($id)->setName($name)->setCount($count);
    }

    public function historyUrlHelper($tmpl, $startUrl) {
        return $GLOBALS[RC]->getRouter()->findHistory($startUrl);
    }

    public function validateCodeHelper($tmpl) {
        return '<span id="validatecodecontainer"><img id="validatecode" name="validatecodename" onclick="javascript:this.src=this.src+1" src="' . BL . 'validatecode.php?" width="130" height="50" style="cursor:pointer" alt="点击刷新"/></span>';
    }

    public function resizeImageHelper($tmpl, $srcFile, $width = NULL, $height = NULL, $default = NULL) {
        $srcFile = Core_Util_Server::urlToPath($srcFile);
        if (file_exists($srcFile) && is_file($srcFile)) {
            $srcPath = pathinfo($srcFile);
            $toFile = DP_TMP . 'resize' . DS . substr($srcPath['filename'], 0, 2) . DS . $srcPath['filename'] . '_' . $width . '_' . $height . '.' . $srcPath['extension'];
            if (!file_exists($toFile)) {
                Soul_Util_FS::makeDirectory(DP_TMP . 'resize' . DS . substr($srcPath['filename'], 0, 2));
                Soul_Util_Image::generateThumbnail($srcFile, $width, $height, $toFile);
            }
            return Core_Util_Server::pathToUrl($toFile);
        }
        if (!is_null($default)) {
            return $default;
        }
        return '';
    }

    public function formatDateHelper($tmpl, $date = NULL, $format = 's') {
        return Soul_Language_Factory::getCulture()->formatDate($date, $format);
    }

}